package com.tank.core;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.tank.bean.User;
import com.tank.util.TankUtil;

public class TankInterceptor extends AbstractInterceptor {
	boolean debug = false;

	boolean mustLogin = true;

	public boolean isDebug() {
		return debug;
	}

	public void setDebug(boolean debug) {
		this.debug = debug;
	}

	public boolean isMustLogin() {
		return mustLogin;
	}

	public void setMustLogin(boolean mustLogin) {
		this.mustLogin = mustLogin;
	}

	@Override
	public String intercept(ActionInvocation ai) throws Exception {
		String result = "login";
		
		User user = TankUtil.getCurrentUser();
		System.out.println("mustlogin="+this.mustLogin+",ip:" + getIP());
		System.out.println(user);
		//必须登录  又  没登录，跳去 登录
		if (mustLogin && user == null)  return result;
		try{
		result = ai.invoke();
		
		}catch(Exception e){
			e.printStackTrace();
		}
		return result;
	}

	public String getIP() {
		HttpServletRequest request = ServletActionContext.getRequest();

		String ip = request.getHeader("Cdn-Src-Ip");

		if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {

			ip = request.getHeader("X-Forwarded-For");

		}

		if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {

			ip = request.getHeader("Proxy-Client-IP");

		}

		if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {

			ip = request.getHeader("WL-Proxy-Client-IP");

		}

		if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {

			ip = request.getHeader("HTTP_CLIENT_IP");

		}

		if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {

			ip = request.getHeader("HTTP_X_FORWARDED_FOR");

		}

		if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {

			ip = request.getRemoteAddr();

		}

		return ip;
	}

}
